package com.egene.tw.activity.member;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.egene.tw.R;
import com.egene.tw.activity.product.ProductItems;
import com.egene.tw.api.EgeneApi;
import com.egene.tw.base.BaseFragment;
import com.egene.tw.dao.UserDao;
import com.egene.tw.model.Reminder;
import com.egene.tw.model.User;
import com.egene.tw.model.UserCenter;
import com.egene.tw.utils.ImageUtil;
import com.egene.tw.utils.JsonUtil;
import com.egene.tw.utils.MToast;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.apache.http.Header;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@EFragment
public class MemberHomeFragment extends BaseFragment {
    View rootView;


    @ViewById
    TextView tvName;
    @ViewById
    TextView tvHealthSource;
    //    @ViewById
//    TextView tvOperateTitle;
//    @ViewById
//    TextView tvOperateContent;
    @ViewById
    ViewStub vsVipTips;
    @ViewById
    ViewStub vsNotVipTips;
    @ViewById
    TextView tvReminder;

    @ViewById
    ImageView ivHead;
    @ViewById
    ImageView ivLineBg;
    @ViewById
    ImageView ivLine;

    View viewTips;

    @Bean
    UserDao userDao;

//    @InstanceState
//    UserCenter mResult;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_member_home, container, false);
        }
        return rootView;
    }

    @AfterViews
    void deal() {
//        if(mResult != null){
//            updateUI(mResult);
//        }else{
        fetchUserCenter();
//        }
    }

    /**
     * 获取用户中心数据集合
     */
    void fetchUserCenter() {
//        String u = "d424e0467e4b4e1684df9e42befdddaa";
        String u = userDao.getUser().getUserID();
        EgeneApi.getUserCenter(u, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if(tvName == null){
                    return;
                }
                UserCenter mResult = JsonUtil.parse(responseBody, UserCenter.class);
                if (mResult != null) {
                    if (mResult.isSuccess()) {
                        updateUI(mResult);
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                MToast.show(R.string.no_network);
            }
        });
    }

    /**
     * 更新ui
     *
     * @param userCenter
     */
    void updateUI(UserCenter userCenter) {
        if (tvName == null) {
            return;
        }
        User user = userDao.getUser();
        tvName.setText(user.getUserName() + getActivity().getString(R.string.hello));
        if (user.getSex().equals("" + User.MALE)) {
            ImageUtil.loadImage(getActivity(), ivHead, R.drawable.man);
        } else if (user.getSex().equals("" + User.FEMALE)) {
            ImageUtil.loadImage(getActivity(), ivHead, R.drawable.woman);
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date birthDay = null;
        try {
            birthDay = simpleDateFormat.parse(user.getBirthdayString());
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //16年的毫秒数
        long dateSpace = 31536000000l * 16;
        Date data = new Date(System.currentTimeMillis() - dateSpace);
        if (birthDay != null) {

            //用16年前的今天与生日比较
            if (data.after(birthDay)) {
                tvHealthSource.setText(getActivity().getString(R.string.health_source) + userCenter.getHealthyvalue());
            } else {
                tvHealthSource.setText(getActivity().getString(R.string.child_health_source) + userCenter.getHealthyvalue());
            }
        } else {
            tvHealthSource.setText(getActivity().getString(R.string.health_source) + userCenter.getHealthyvalue());
        }

        updateTips(userCenter);
        updateHealthLine(userCenter.getHealthyvalue().intValue());
        updateReminder(userCenter.getReminder());
    }

    /**
     * 更新健康达人值
     *
     * @param values
     */
    void updateHealthLine(int values) {
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) ivLine.getLayoutParams();
        lp.width = ivLineBg.getWidth() * values / 100;
        ivLine.setLayoutParams(lp);
    }

    /**
     * 更新温馨提示
     *
     * @param reminderList
     */
    void updateReminder(List<Reminder> reminderList) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < reminderList.size(); i++) {
            if (i != 0) {
                sb.append("\n\n");
            }
            Reminder reminder = reminderList.get(i);
            sb.append(i + 1).append(".").append(reminder.getContent());
            tvReminder.setText(sb.toString());
        }
    }

    void updateTips(UserCenter userCenter) {
        if (viewTips != null) {
            return;
        }
        if (userCenter.isSuccess()) {
            viewTips = vsVipTips.inflate();
            TextView tvOperateTitle = (TextView) viewTips.findViewById(R.id.tvOperateTitle);
            TextView tvOperateContent = (TextView) viewTips.findViewById(R.id.tvOperateContent);
            tvOperateTitle.setText(userCenter.getProgresstitle());
            tvOperateContent.setText(userCenter.getProgressdetail());
        } else {
            viewTips = vsNotVipTips.inflate();
        }
        viewTips.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MemberViewPagerFragment fragment = (MemberViewPagerFragment) getActivity().getSupportFragmentManager().getFragments().get(0);
                fragment.goToCheckReport();
            }
        });
    }

    @Click(R.id.llAdult)
    void adult() {
        MemberViewPagerFragment fragment = (MemberViewPagerFragment) getActivity().getSupportFragmentManager().getFragments().get(0);
        fragment.showList(ProductItems.ADULT.getIdx());
    }

    @Click(R.id.llChild)
    void child() {
        MemberViewPagerFragment fragment = (MemberViewPagerFragment) getActivity().getSupportFragmentManager().getFragments().get(0);
        fragment.showList(ProductItems.CHILD.getIdx());

    }

    @Click(R.id.llBeauty)
    void beauty() {
        if(getActivity() == null){
            return;
        }
        if(getActivity().getSupportFragmentManager() == null){
            return;
        }
        if(getActivity().getSupportFragmentManager().getFragments().get(0) instanceof MemberViewPagerFragment){
            MemberViewPagerFragment fragment = (MemberViewPagerFragment) getActivity().getSupportFragmentManager().getFragments().get(0);
            fragment.showList(ProductItems.BEAUTY.getIdx());
        }
    }

    @Click(R.id.tvHealthyPunch)
    void punch() {
        HealthPunchActivity_.intent(getActivity()).start();
    }

}
